package models

import (
	"fmt"
	"strings"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

type Records struct {
	Id         int       `orm:"column(id);auto"`
	Sn         string    `orm:"column(sn);size(255);null" description:"学号"`
	Createtime time.Time `orm:"column(createtime);type(datetime);null" description:"登记时间"`
	Now        string    `orm:"column(now);null" description:"登记日期"`
	Comments   string    `orm:"column(comments);size(255);null" description:"备注"`
	Record     int       `orm:"column(record);size(20);null" description:"分值"`
	Course     int       `orm:"column(course_id);size(20);null" description:"分值"`
	CourseCn   string    `orm:"column(course_cn);size(255);null" description:"备注"`
}

func (t *Records) TableName() string {
	return "records"
}

func init() {
	orm.RegisterModel(new(Records))
}

// AddRecords insert a new Records into database and returns
// last inserted Id on success.
func AddRecords(m *Records) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetRecordsById retrieves Records by Id. Returns error if
// Id doesn't exist
func GetRecordsById(id int) (v *Records, err error) {
	o := orm.NewOrm()
	v = &Records{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllRecords retrieves all Records matches certain condition. Returns empty list if
// no records exist
func GetStudentRecords(query map[string]string, offset int64, limit int64) (ml []Records, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Records))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}

	var l []Records
	if _, err = qs.OrderBy("-id").Limit(limit, offset).All(&l); err == nil {
		return l, nil
	}
	return nil, err
}

// UpdateRecords updates Records by Id and returns error if
// the record to be updated doesn't exist
func UpdateRecordsById(m *Records) (err error) {
	o := orm.NewOrm()
	v := Records{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteRecords deletes Records by Id and returns error if
// the record to be deleted doesn't exist
func DeleteRecords(id int) (err error) {
	o := orm.NewOrm()
	v := Records{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Records{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}
